package com.szzg10.thinking.chapter18;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;

public class LockingMappedFiles {

	private static FileChannel channel;
	
	private static int LENGTH = 0x8FFFFFF;
	
	public static void main(String[] args) throws IOException {
		File file = new File(BasicFileOutput.FILE_NAME_OUT);
		RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
		channel = randomAccessFile.getChannel();
		MappedByteBuffer mappedByteBuffer = channel.map(FileChannel.MapMode.READ_WRITE, 0, LENGTH);
		
		for(int i = 0; i < LENGTH; i++) {
			mappedByteBuffer.put((byte)'x');
		}
		
		new LockAndModify(mappedByteBuffer, 0, 0 + LENGTH / 3);
		new LockAndModify(mappedByteBuffer, LENGTH / 2, LENGTH / 2 + LENGTH /4);
	}
	
	private static class LockAndModify extends Thread {
		private ByteBuffer byteBuffer;
		private int start;
		private int end;
		
		public LockAndModify(ByteBuffer aByteBuffer, int start, int end) {
			this.start = start;
			this.end = end;
			
			aByteBuffer.limit(end);
			aByteBuffer.position(start);
			
			byteBuffer = aByteBuffer.slice();
			start();
		}
		
		@Override
		public void run() {
			try {
				FileLock fileLock = channel.lock(start, end, false);
				System.out.println("Locked: " + start + " to " + end);
				
				while(byteBuffer.position() < byteBuffer.limit() - 1) {
					byteBuffer.put((byte)(byteBuffer.get() + 1));
				}
				
				fileLock.release();
				System.out.println("Released: " + start + " to " + end);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
